package com.scut.campus.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scut.campus.context.BaseContext;
import com.scut.campus.dto.CommentDto;
import com.scut.campus.entity.Comment;
import com.scut.campus.mapper.CommentMapper;
import com.scut.campus.query.CommentQuery;
import com.scut.campus.query.MoreSubCommentPageQuery;
import com.scut.campus.service.CommentService;
import com.scut.campus.service.LikeService;
import com.scut.campus.utils.DateTimeUtil;
import com.scut.campus.vo.CommentVo;
import com.scut.campus.vo.SubCommentVo;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private LikeService likeService;

    @Override
    public void insertComment(CommentDto commentDto) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDto, comment);
        comment.setUserId(BaseContext.getCurrentId());
        this.save(comment);
    }

    public List<CommentVo> getCommentsByPostId(CommentQuery commentQuery) {
        if (Strings.isBlank(commentQuery.getLastEndKey())) {
            commentQuery.setLastEndKey("0");
        }
        // 获取所有顶级评论
        List<CommentVo> topComments = commentMapper.queryTopComments(commentQuery);

        // 获取所有顶级评论的 commentId，用于后续查询子评论
        List<String> commentIds = topComments.stream()
                .map(CommentVo::getCommentId)
                .collect(Collectors.toList());
        Map<String, String> isCommentLiked = likeService.isCommenttLiked(commentIds);

        if (!commentIds.isEmpty()) {
            // 第二次查询：根据顶级评论的 commentId 查询子评论
            List<SubCommentVo> subComments = commentMapper.querySubComments(commentIds);

            List<String> subCommentIds = subComments.stream()
                    .map(SubCommentVo::getCommentId)
                    .collect(Collectors.toList());
            Map<String, String> isSubCommentLiked = likeService.isCommenttLiked(subCommentIds);

            // 按 commentId 分组，得到 Map<Long, List<SubCommentVo>>
            Map<String, List<SubCommentVo>> commentsGroupedByCommentId = subComments.stream()
                    .map(subComment -> {
                        DateTimeUtil.converToDateTime(subComment.getCreateTime());
                        subComment.setLiked(Strings.isNotBlank(isSubCommentLiked.get(subComment.getUserId())));
                        return subComment; // 返回更新后的对象
                    })
                    .collect(Collectors.groupingBy(SubCommentVo::getLastId));

            // 将子评论合并到对应的顶级评论中
            for (CommentVo commentVo : topComments) {
                commentVo.setCreateTime(DateTimeUtil.converToDateTime(commentVo.getCreateTime()));
                commentVo.setSubComments(commentsGroupedByCommentId.get(commentVo.getCommentId()));
                commentVo.setLikeNum(likeService.countCommentLike(commentVo.getCommentId()));
                commentVo.setLiked(Strings.isNotBlank(isCommentLiked.get(BaseContext.getCurrentId())));
            }

        }
        // 返回合并后的顶级评论列表
        return topComments;
    }

    @Override
    public void deleteByPostId(String postId) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Comment::getPostId, postId);
        this.remove(lambdaQueryWrapper);
    }

    @Override
    public long commentCount(String postId) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Comment::getPostId, postId)
                .isNull(Comment::getLastCommentId);
        return this.count(lambdaQueryWrapper);
    }

    @Override
    public List<SubCommentVo> queryMoreSubcomment(MoreSubCommentPageQuery pageQuery) {
        List<SubCommentVo> subCommentVoList = commentMapper.queryMoreSubComments(pageQuery);

        List<String> commentIds = subCommentVoList.stream()
                .map(SubCommentVo::getCommentId)
                .collect(Collectors.toList());
        Map<String, String> isSubCommentLiked = likeService.isCommenttLiked(commentIds);
        for (SubCommentVo subCommentVo : subCommentVoList) {
            subCommentVo.setCreateTime(DateTimeUtil.converToDateTime(subCommentVo.getCreateTime()));

            subCommentVo.setLiked(Strings.isNotBlank(isSubCommentLiked.get(BaseContext.getCurrentId())));
        }


        return commentMapper.queryMoreSubComments(pageQuery);
    }
}
